import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

/// <summary>
/// todo: 查看大图
/// author：zwb
/// dateTime：2021/7/23 15:23
/// filePath：common/widgets/show_image_widget.dart
/// desc: 图片缩放 + 图片保存 ， 支持 File 、 项目静态图片、网络图片 ， 网络图片预览带缓存
/// 注：File时 传入的 images 是 File.path
/// <summary>
/// 示例
// ShowImageWidget(
//   currentIndex: 0,
//   images: [ConstantPath.imagesPath+"18e76135e89d3aa1b5e1cf6b165fae23.jpeg"],
//   onLongPressPath: (v){
//     print(v);
//     Get.back();
//   },
// )
class ShowImageWidget extends StatefulWidget {
  ShowImageWidget( {Key key,  this.images, this.currentIndex : 0, this.controller,this.onLongPressPath, this.max:2, this.min:1, this.showTop: true, this.onLongPressStart})
      : super(key: key);
  final List<String> images; // 资源图片 支持网络图片、本地图片、静态资源图片
  final int currentIndex; // 当前图片
  final PageController controller; // 控制器
  final double max; // 最大缩放
  final double min; // 最新缩放
  final bool showTop; // 是否显示顶部数字栏
  Function(LongPressStartDetails) onLongPressStart; // 自定义长按事件
  Function(String) onLongPressPath; // 长按回调事件
  @override
  _ShowImageWidgetState createState() => _ShowImageWidgetState();
}

class _ShowImageWidgetState extends State<ShowImageWidget> {
  int currentIndex = 0;
  PageController pageController =  PageController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.controller != null) pageController = widget.controller;
    if(widget.currentIndex!=null) currentIndex = widget.currentIndex;
    Future.delayed( Duration.zero, (){
      setState(() {
        if(widget.images.length >1) pageController.jumpToPage(widget.currentIndex);
      });
    }
    );
  }

  /// todo：校验url类型
  dynamic checkImg(String url){
    if(url.startsWith("http://") || url.startsWith("https://")){
      // 网络图片
      return CachedNetworkImageProvider(url);
    }else if(url.startsWith("assets/")){
      // 静态资源图片
      return AssetImage(url);
    }else{
      // 本地图片文件
      return FileImage(File(url));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        elevation: 0.0,
        backgroundColor: Colors.transparent,
        centerTitle: true,
        title: Text(widget.showTop ? "${(currentIndex+1) > widget.images.length ? 1: (currentIndex+1) }/${widget.images.length}" : '',style: TextStyle(color: Colors.white),),
        leading: IconButton(icon: Icon(Icons.chevron_left,color: Colors.white,), onPressed: ()=>Navigator.of(context).pop()),
      ),
      body: widget.images.length == 0 ? SizedBox() : GestureDetector(
        onLongPressStart: widget.onLongPressPath == null ? null: (v){
          widget.onLongPressStart !=null ? widget.onLongPressStart(v):
          showModalBottomSheet(context: context, builder: (ctx){
            return Container(
              height: 50,
              child: MaterialButton(
                child: Text("保存图片"),
                onPressed: (){
                  widget.onLongPressPath(widget.images[currentIndex]);
                },
              ),
            );
          });
        },
        child: PhotoViewGallery.builder(
          builder: (BuildContext context, int index) {
            return PhotoViewGalleryPageOptions(
              imageProvider: CachedNetworkImageProvider("${widget.images[index]}",),
              initialScale: PhotoViewComputedScale.contained * 1.0,
              minScale: PhotoViewComputedScale.contained * widget.min,
              maxScale: PhotoViewComputedScale.contained * widget.max,
            );
          },
          scrollPhysics: const ClampingScrollPhysics(),
          loadingBuilder: (context, event) =>Center(
            child: Container(
              width: 20.0,
              height: 20.0,
              child: CircularProgressIndicator( value: 1,),
              color: Colors.transparent,
            ),
          ),
          itemCount: widget.images.length,
          pageController: pageController,
          backgroundDecoration: BoxDecoration( color: Colors.black,),
          onPageChanged: (v) => setState(() => currentIndex = v),
        ),
      ),
    );
  }
}
